package com.gz.mylife.adapter;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import org.xutils.x;
import org.xutils.image.ImageOptions;

import com.gz.mylife.R;
import com.gz.mylife.app.FragmentMallBrandedProductsActivity;
import com.gz.mylife.app.Browser;
import com.gz.mylife.app.Notices;
import com.gz.mylife.po.ActivitiesInfoWrapper;
import com.gz.mylife.util.ImageUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.zl.smartmall.library.po.ActivitiesBrandIconInfo;
import com.zl.smartmall.library.po.ActivitiesCommoditiesInfo;
import com.zl.smartmall.library.po.ActivitiesInfoType;
import com.zl.smartmall.library.po.ActivitiesLatestNoticeInfo;
import com.zl.smartmall.library.po.ActivitiesThemeMarketInfo;
import com.zl.smartmall.library.po.BaseActivitiesInfo;
import com.zl.smartmall.library.po.CountDownInfo;
import com.zl.smartmall.library.util.CrashHandler;
import com.zl.smartmall.library.util.Tools;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class FragmentMallAdapter<T extends BaseActivitiesInfo> extends BaseAdapter implements OnClickListener, OnItemClickListener {

	private static final String TAG = FragmentMallAdapter.class.getSimpleName();
	private Context mContext;
	private DisplayImageOptions mIconOptions;
	private LayoutInflater mInflater;
	private List<T> mBaseActivitiesInfos;
	private QuickAdapter<ActivitiesBrandIconInfo> mRecommendMerchantAdapter;
	
	public FragmentMallAdapter(Context context, List<T> baseActivitiesInfos) {
		mBaseActivitiesInfos = new ArrayList<T>(baseActivitiesInfos);
		mContext = context;
		mInflater = LayoutInflater.from(context);
		mIconOptions = ImageUtils.buildTransparentOptions();
		mRecommendMerchantAdapter = buildRecommendMerchantAdater();
	}
	
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return mBaseActivitiesInfos.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return mBaseActivitiesInfos.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}
	
	@Override
	public int getItemViewType(int position) {
		// TODO Auto-generated method stub
		return ((BaseActivitiesInfo) getItem(position)).getActivitiesInfoType();
	}
	
	@Override
	public int getViewTypeCount() {
		// TODO Auto-generated method stub
		return 6;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		BaseViewHolder baseViewHolder = null;
		if(convertView == null) {
			CrashHandler.d(TAG, "创建convertView");
			switch (getItemViewType(position)) {
			case ActivitiesInfoType.TYPE_CLASSIFY:
				break;
				
			case ActivitiesInfoType.TYPE_COMMODITIES:
				convertView = mInflater.inflate(R.layout.fragment_mall_commodities, parent, false);
				break;
				
			case ActivitiesInfoType.TYPE_COMMODITIES_ITEM:
				convertView = mInflater.inflate(R.layout.fragment_mall_commodities_item, parent, false);
				baseViewHolder = new CommoditiesViewHolder();
				initCommoditiesItem(convertView, (CommoditiesViewHolder) baseViewHolder);
				break;
				
			case ActivitiesInfoType.TYPE_NOTICE:
				convertView = mInflater.inflate(R.layout.fragment_mall_latest_notice, parent, false);
				baseViewHolder = new LatestNoticeViewHolder();
				initLatestNotice(convertView, (LatestNoticeViewHolder) baseViewHolder);
				break;
				
			case ActivitiesInfoType.TYPE_RECOMMEND_MERCHANT:
				convertView = mInflater.inflate(R.layout.fragment_mall_merchant, parent, false);
				((GridView) convertView.findViewById(R.id.gridview_classify)).setAdapter(mRecommendMerchantAdapter);
				((GridView) convertView.findViewById(R.id.gridview_classify)).setOnItemClickListener(this);
				break;
				
			case ActivitiesInfoType.TYPE_THEME_MARKET:
				convertView = mInflater.inflate(R.layout.fragment_mall_theme_market, parent, false);
				baseViewHolder = new ThemeMarketViewHolder();
				initThemeMarket(convertView, (ThemeMarketViewHolder) baseViewHolder);
				break;
			}
			convertView.setTag(baseViewHolder);
			
		}else {
			baseViewHolder = (BaseViewHolder) convertView.getTag();
		}
		
		switch (getItemViewType(position)) {
		case ActivitiesInfoType.TYPE_CLASSIFY:
			break;
			
		case ActivitiesInfoType.TYPE_COMMODITIES:
			break;
			
		case ActivitiesInfoType.TYPE_COMMODITIES_ITEM:
			setCommoditiesItem((CommoditiesViewHolder) baseViewHolder, (ActivitiesCommoditiesInfo) getItem(position));
			break;
			
		case ActivitiesInfoType.TYPE_NOTICE:
			setLatestNotice((LatestNoticeViewHolder) baseViewHolder, (ActivitiesInfoWrapper<ActivitiesLatestNoticeInfo>) getItem(position));
			break;
			
		case ActivitiesInfoType.TYPE_RECOMMEND_MERCHANT:
			setRecommendMerchant((ActivitiesInfoWrapper<ActivitiesBrandIconInfo>) getItem(position));
			break;
			
		case ActivitiesInfoType.TYPE_THEME_MARKET:
			setThemeMarket((ThemeMarketViewHolder) baseViewHolder, (ActivitiesInfoWrapper<ActivitiesThemeMarketInfo>) getItem(position));
			break;
		}
		
		return convertView;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = null;
		switch (v.getId()) {
		case R.id.layout_theme_1:
		case R.id.layout_theme_2:
		case R.id.layout_theme_3:
		case R.id.layout_theme_4:
		case R.id.layout_theme_5:
			if(v.getTag() != null) {
				intent = new Intent(mContext, FragmentMallBrandedProductsActivity.class);
				intent.putExtra("name", ((ActivitiesThemeMarketInfo) v.getTag()).getName());
				intent.putExtra("brandId", ((ActivitiesThemeMarketInfo) v.getTag()).getActivitiesId());
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				mContext.startActivity(intent);
			}
			break;

		case R.id.layout_notice_item:
			ActivitiesLatestNoticeInfo activitiesLatestNoticeInfo = 
				((LatestNoticeItemViewHolder) v.getTag()).activitiesLatestNoticeInfo;
			intent = new Intent(mContext, Browser.class);
			intent.putExtra("url", activitiesLatestNoticeInfo.getUrl());
			intent.putExtra("title", "最新公告");
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			mContext.startActivity(intent);
			break;
			
		case R.id.tv_more:
			intent = new Intent(mContext, Notices.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			mContext.startActivity(intent);
			break;
			
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		// TODO Auto-generated method stub
		ActivitiesBrandIconInfo activitiesBrandIconInfo = mRecommendMerchantAdapter.getItem((int) id);
		Intent intent = new Intent(mContext, FragmentMallBrandedProductsActivity.class);
		intent.putExtra("name", activitiesBrandIconInfo.getName());
		intent.putExtra("brandId", activitiesBrandIconInfo.getActivitiesId());
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		mContext.startActivity(intent);
	}

	public void add(T baseActivitiesInfo) {
		mBaseActivitiesInfos.add(baseActivitiesInfo);
	}
	
	public void addAll(List<T> baseActivitiesInfos) {
		mBaseActivitiesInfos.addAll(baseActivitiesInfos);
	}
	
	public void clear() {
		mBaseActivitiesInfos.clear();
	}
	
	private QuickAdapter<ActivitiesBrandIconInfo> buildRecommendMerchantAdater(){
		return new QuickAdapter<ActivitiesBrandIconInfo>(mContext, R.layout.fragment_mall_merchant_item, new ArrayList<ActivitiesBrandIconInfo>()) {
			
			@Override
			protected void convert(BaseAdapterHelper helper, ActivitiesBrandIconInfo item) {
				helper.setImageUrl(R.id.iv_picture, item.getIcon(), mIconOptions)
					  .setText(R.id.tv_name, item.getName());
				
				if(item.getActivitiesId() == -1){
					helper.getView().setBackgroundResource(R.color.white);
					
				}else{
					helper.getView().setBackgroundResource(R.drawable.list_item_white_selector);
				}
			}
		};
	}

	private void initCommoditiesItem(View convertView, CommoditiesViewHolder commoditiesViewHolder) {
		// TODO Auto-generated method stub
		commoditiesViewHolder.currentCost = (TextView) convertView.findViewById(R.id.tv_current_cost);
		commoditiesViewHolder.discount = (TextView) convertView.findViewById(R.id.tv_discount);
		commoditiesViewHolder.icon = (ImageView) convertView.findViewById(R.id.iv_product);
		commoditiesViewHolder.intro = (TextView) convertView.findViewById(R.id.tv_product_intro);
		commoditiesViewHolder.originalCost = (TextView) convertView.findViewById(R.id.tv_original_cost);
		commoditiesViewHolder.shopName = (TextView) convertView.findViewById(R.id.tv_shop_name);
		commoditiesViewHolder.layoutLabel = (LinearLayout) convertView.findViewById(R.id.layout_labels);
	}
	
	private void setCommoditiesItem(CommoditiesViewHolder commoditiesViewHolder, ActivitiesCommoditiesInfo activitiesCommoditiesInfo) {
		commoditiesViewHolder.originalCost.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
		for(int i = 0; i < commoditiesViewHolder.layoutLabel.getChildCount();i++){
			commoditiesViewHolder.layoutLabel.getChildAt(i).setVisibility(View.INVISIBLE);
		}
		for(int i = 0; i < activitiesCommoditiesInfo.getLabel().length && i < commoditiesViewHolder.layoutLabel.getChildCount();i++){
			commoditiesViewHolder.layoutLabel.getChildAt(i).setVisibility(View.VISIBLE);
			((TextView)commoditiesViewHolder.layoutLabel.getChildAt(i)).setText(activitiesCommoditiesInfo.getLabel()[i]);
		}
		double disCount = activitiesCommoditiesInfo.getCurrentCost() / activitiesCommoditiesInfo.getOriginalCost();
		String disCountStr = activitiesCommoditiesInfo.getCurrentCost() == activitiesCommoditiesInfo.getOriginalCost() ? 
				"无折扣":new DecimalFormat("0.0").format(disCount*10)+"折";
		
		commoditiesViewHolder.intro.setText(activitiesCommoditiesInfo.getProductTitle());
		commoditiesViewHolder.originalCost.setText(new DecimalFormat("0.00").format(activitiesCommoditiesInfo.getOriginalCost()));
		commoditiesViewHolder.currentCost.setText("￥" + new DecimalFormat("0.00").format(activitiesCommoditiesInfo.getCurrentCost()));
		commoditiesViewHolder.discount.setText(disCountStr);
		commoditiesViewHolder.shopName.setText(activitiesCommoditiesInfo.getShopName());
		
		if(activitiesCommoditiesInfo.getCurrentCost() == activitiesCommoditiesInfo.getOriginalCost()){
			commoditiesViewHolder.discount.setVisibility(View.GONE);
		}else{
			commoditiesViewHolder.discount.setVisibility(View.VISIBLE);
		}
		
		ImageLoader.getInstance().displayImage(activitiesCommoditiesInfo.getPicture(), commoditiesViewHolder.icon, mIconOptions);
	}
	
	private void initLatestNotice(View convertView, LatestNoticeViewHolder latestNoticeViewHolder) {
		latestNoticeViewHolder.tvMore = (TextView) convertView.findViewById(R.id.tv_more);
		latestNoticeViewHolder.tvMore.setOnClickListener(this);
		latestNoticeViewHolder.layoutLatestNoticeItem = (LinearLayout) convertView.findViewById(R.id.layout_latest_notice_item);
	}
	
	private void setLatestNotice(LatestNoticeViewHolder latestNoticeViewHolder, ActivitiesInfoWrapper<ActivitiesLatestNoticeInfo> activitiesInfoWrapper) {
		List<ActivitiesLatestNoticeInfo> activitiesLatestNoticeInfos = activitiesInfoWrapper.getDataset();
		//如果layout的子view为零, 或者子view数量和activitiesLatestNoticeInfos数量不一致
		if(latestNoticeViewHolder.layoutLatestNoticeItem.getChildCount() < 1 ||
				latestNoticeViewHolder.layoutLatestNoticeItem.getChildCount() != activitiesLatestNoticeInfos.size()) {
			latestNoticeViewHolder.layoutLatestNoticeItem.removeAllViews();			
			for(int i = 0; i < activitiesLatestNoticeInfos.size(); i++) {
				LatestNoticeItemViewHolder latestNoticeItemViewHolder = new LatestNoticeItemViewHolder();
				View latestNoticeItem = mInflater.inflate(R.layout.fragment_mall_latest_notice_item, latestNoticeViewHolder.layoutLatestNoticeItem, false);
				latestNoticeItemViewHolder.icon = (ImageView) latestNoticeItem.findViewById(R.id.iv_icon);
				latestNoticeItemViewHolder.title = (TextView) latestNoticeItem.findViewById(R.id.tv_title);
				latestNoticeItemViewHolder.content = (TextView) latestNoticeItem.findViewById(R.id.tv_content);
				latestNoticeItemViewHolder.viewCount = (TextView) latestNoticeItem.findViewById(R.id.tv_view_count);
				latestNoticeItemViewHolder.label = (TextView) latestNoticeItem.findViewById(R.id.tv_label);
				//持有数据集
				latestNoticeItemViewHolder.activitiesLatestNoticeInfo = activitiesLatestNoticeInfos.get(i);
				latestNoticeItem.setTag(latestNoticeItemViewHolder);
				latestNoticeItem.setOnClickListener(this);
				latestNoticeViewHolder.layoutLatestNoticeItem.addView(latestNoticeItem);
				//加分割线
				if(i < activitiesLatestNoticeInfos.size() - 1) {
					View divider = new View(mContext);
					divider.setBackgroundResource(R.drawable.divider_deep);
					latestNoticeViewHolder.layoutLatestNoticeItem.addView(divider);
					LinearLayout.LayoutParams params= (android.widget.LinearLayout.LayoutParams) divider.getLayoutParams();
					params.width = LayoutParams.MATCH_PARENT;
					params.height = Tools.dip2px(mContext, 0.5f);
					params.leftMargin = Tools.dip2px(mContext, 14);
					params.rightMargin = Tools.dip2px(mContext, 14);
//					params.topMargin = Tools.dip2px(mContext, 7);
				}
			}
		
		}
		
		int datasetIndex = 0;
		for(int i = 0; i < latestNoticeViewHolder.layoutLatestNoticeItem.getChildCount(); i++) {
			LatestNoticeItemViewHolder latestNoticeItemViewHolder = (LatestNoticeItemViewHolder) 
					latestNoticeViewHolder.layoutLatestNoticeItem.getChildAt(i).getTag();
			//由于上面添加了分割线, 所以会出现tag为空情况
			if(latestNoticeItemViewHolder != null) {
				latestNoticeItemViewHolder.content.setText(activitiesLatestNoticeInfos.get(datasetIndex).getContent());
				latestNoticeItemViewHolder.title.setText(activitiesLatestNoticeInfos.get(datasetIndex).getTitle());
				latestNoticeItemViewHolder.viewCount.setText(activitiesLatestNoticeInfos.get(datasetIndex).getViewCount() + "浏览");
				if(TextUtils.isEmpty(activitiesLatestNoticeInfos.get(datasetIndex).getTag())) {
					latestNoticeItemViewHolder.label.getLayoutParams().width = 0;
					((RelativeLayout.LayoutParams) latestNoticeItemViewHolder.viewCount.getLayoutParams())
						.rightMargin = 0;
					
				}else {
					((RelativeLayout.LayoutParams) latestNoticeItemViewHolder.viewCount.getLayoutParams())
						.rightMargin = Tools.dip2px(mContext, 13);
					latestNoticeItemViewHolder.label.getLayoutParams().width = LayoutParams.WRAP_CONTENT;
					latestNoticeItemViewHolder.label.setText(activitiesLatestNoticeInfos.get(datasetIndex).getTag());
				}
				ImageLoader.getInstance().displayImage(
						activitiesLatestNoticeInfos.get(datasetIndex).getIcon(), 
						latestNoticeItemViewHolder.icon, 
						ImageUtils.buildTransparentOptions());
				datasetIndex++;
			}
		}
		
	}

	private void setRecommendMerchant(ActivitiesInfoWrapper<ActivitiesBrandIconInfo> activitiesInfoWrapper) {
		// TODO Auto-generated method stub
		List<ActivitiesBrandIconInfo> activitiesBrandIconInfos = activitiesInfoWrapper.getDataset();
		mRecommendMerchantAdapter.clear();
		mRecommendMerchantAdapter.addAll(activitiesBrandIconInfos);
	}
	
	private void initThemeMarket(View convertView, ThemeMarketViewHolder themeMarketViewHolder) {
		// TODO Auto-generated method stub
		themeMarketViewHolder.layoutCountDown = convertView.findViewById(R.id.layout_countdown);
		themeMarketViewHolder.ivTheme = new ImageView[]{
				(ImageView) convertView.findViewById(R.id.iv_theme_icon1),
				(ImageView) convertView.findViewById(R.id.iv_theme_icon2),
				(ImageView) convertView.findViewById(R.id.iv_theme_icon3),
				(ImageView) convertView.findViewById(R.id.iv_theme_icon4),
				(ImageView) convertView.findViewById(R.id.iv_theme_icon5)
		};
		themeMarketViewHolder.tvThemeIntro = new TextView[]{
				(TextView) convertView.findViewById(R.id.tv_theme_intro_1),
				(TextView) convertView.findViewById(R.id.tv_theme_intro_2),
				(TextView) convertView.findViewById(R.id.tv_theme_intro_3),
				(TextView) convertView.findViewById(R.id.tv_theme_intro_4),
				(TextView) convertView.findViewById(R.id.tv_theme_intro_5)
		};
		themeMarketViewHolder.tvThemeTitle = new TextView[]{
				(TextView) convertView.findViewById(R.id.tv_theme_title_1),
				(TextView) convertView.findViewById(R.id.tv_theme_title_2),
				(TextView) convertView.findViewById(R.id.tv_theme_title_3),
				(TextView) convertView.findViewById(R.id.tv_theme_title_4),
				(TextView) convertView.findViewById(R.id.tv_theme_title_5)
		};
		themeMarketViewHolder.layoutTheme = new View[]{
				convertView.findViewById(R.id.layout_theme_1),
				convertView.findViewById(R.id.layout_theme_2),
				convertView.findViewById(R.id.layout_theme_3),
				convertView.findViewById(R.id.layout_theme_4),
				convertView.findViewById(R.id.layout_theme_5),
		};
		
		for(View view : themeMarketViewHolder.layoutTheme) {
			view.setOnClickListener(this);
		}
	}
	
	private void setThemeMarket(ThemeMarketViewHolder themeMarketViewHolder, ActivitiesInfoWrapper<ActivitiesThemeMarketInfo> activitiesInfoWrapper) {
		// TODO Auto-generated method stub
		List<ActivitiesThemeMarketInfo> activitiesThemeMarketInfos = activitiesInfoWrapper.getDataset();
		for(int i = 0; i < activitiesThemeMarketInfos.size(); i++) {
			themeMarketViewHolder.tvThemeIntro[i].setText(activitiesThemeMarketInfos.get(i).getIntro());
			themeMarketViewHolder.tvThemeTitle[i].setText(activitiesThemeMarketInfos.get(i).getName());
			themeMarketViewHolder.layoutTheme[i].setTag(activitiesThemeMarketInfos.get(i));
			/*ImageLoader.getInstance().displayImage(
					activitiesThemeMarketInfos.get(i).getPicture(), themeMarketViewHolder.ivTheme[i], mIconOptions);*/
			ImageOptions imageOptions = new ImageOptions.Builder()
			.setIgnoreGif(true)
			.setImageScaleType(ImageView.ScaleType.CENTER_CROP)
			.setCrop(true) //设置大小
			.build();
			x.image().bind(themeMarketViewHolder.ivTheme[i], activitiesThemeMarketInfos.get(i).getPicture(),imageOptions);
			if(i == 0) {
				setCountDown(themeMarketViewHolder, activitiesThemeMarketInfos.get(i).getCountDownInfo());
			}
		}
	}
	
	private void setCountDown(ThemeMarketViewHolder themeMarketViewHolder, CountDownInfo countDownInfo) {
		if(countDownInfo != null) {
			//目前不打开倒计时
			themeMarketViewHolder.layoutCountDown.setVisibility(View.GONE);
			RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) themeMarketViewHolder.ivTheme[0].getLayoutParams();
			params.addRule(RelativeLayout.BELOW, R.id.layout_countdown);
			
		}else {
			themeMarketViewHolder.layoutCountDown.setVisibility(View.GONE);
			RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) themeMarketViewHolder.ivTheme[0].getLayoutParams();
			params.addRule(RelativeLayout.BELOW, R.id.tv_theme_intro_1);
		}
	}

	static interface BaseViewHolder{}
	
	static class LatestNoticeViewHolder implements BaseViewHolder {
		TextView tvMore;
		LinearLayout layoutLatestNoticeItem;
	}
	
	static class LatestNoticeItemViewHolder {
		ImageView icon;
		TextView title;
		TextView content;
		TextView viewCount;
		TextView label;
		ActivitiesLatestNoticeInfo activitiesLatestNoticeInfo;
	}
	
	static class ThemeMarketViewHolder implements BaseViewHolder {
		ImageView[] ivTheme;
		TextView[] tvThemeTitle;
		TextView[] tvThemeIntro;
		View[] layoutTheme;
		View layoutCountDown;
	}
	
	static class CommoditiesViewHolder implements BaseViewHolder {
		ImageView icon;
		TextView intro;
		TextView discount;
		TextView currentCost;
		TextView originalCost;
		TextView shopName;
		LinearLayout layoutLabel;
	}

}
